package mdt.action;

import org.tigris.gef.base.Editor;
import org.tigris.gef.base.Globals;
import org.tigris.gef.graph.MutableGraphSupport;
import org.tigris.gef.presentation.Fig;
import org.tigris.gef.presentation.FigGroup;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.*;

/**
 * Created by xiaobyu on 7/15/2016.
 */
public class UngroupAction extends AbstractAction {

    public UngroupAction() {
        super("Ungroup");
        putValue(Action.SMALL_ICON, new ImageIcon(FontBoldAction.class.getResource("/resources/ungroup-16.png")));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        ArrayList<Fig> ungroupedFigs = new ArrayList<>();
        Editor currentEditor = Globals.curEditor();
        List<Fig> selectedFigs = currentEditor.getSelectionManager().getSelectedFigs();

        for (Fig fig : selectedFigs) {
            if (fig.getClass().isAssignableFrom(FigGroup.class)) {
                FigGroup fg = (FigGroup)fig;
                for (Fig f : fg.getFigs()) {
                    currentEditor.add(f);
                    ungroupedFigs.add(f);
                }

                currentEditor.remove(fg);
            }
        }

        MutableGraphSupport.enableSaveAction();
        currentEditor.getSelectionManager().deselectAll();
        currentEditor.getSelectionManager().selectFigs(ungroupedFigs);
    }
}
